# PNAS Replication Entry Point
# Run this script to replicate all analyses
#
# Usage:
#   Command line: Rscript run_replication.R
#   R console:    source("run_replication.R")

# Set working directory to script location (for Rscript execution)
if (!interactive()) {
  args <- commandArgs(trailingOnly = FALSE)
  script_path <- sub("--file=", "", args[grep("--file=", args)])
  if (length(script_path) > 0) {
    setwd(dirname(script_path))
  }
}

message("Working directory: ", getwd())

# Configure package installation options
ppm_url <- "https://packagemanager.posit.co/cran/latest"
options(
  repos = c(CRAN = ppm_url),
  pkgType = "binary",
  install.packages.compile.from.source = "never"
)

# Install here package fresh (avoid cache corruption issues)
message("Setting up here package...")
tryCatch({
  library(here)
}, error = function(e) {
  message("here package not working, reinstalling fresh...")
  # Remove potentially corrupt installation
  try(remove.packages("here"), silent = TRUE)
  install.packages("here", repos = ppm_url, type = "binary")
  library(here)
})
here::i_am("run_replication.R")

# Restore packages using renv
message("Checking package environment...")
if (file.exists("renv.lock")) {
  if (!requireNamespace("renv", quietly = TRUE)) {
    install.packages("renv", repos = ppm_url, type = "binary")
  }
  
  # Configure renv to prefer binaries; use cache so restore gets binaries (avoids source compile failures)
  options(
    renv.config.ppm.enabled = TRUE,
    renv.config.pak.enabled = FALSE,
    renv.config.cache.enabled = TRUE
  )
  
  # Attempt restore
  tryCatch({
    renv::restore(prompt = FALSE)
  }, error = function(e) {
    message("[WARN] renv::restore() failed: ", conditionMessage(e))
    message("")
    message("Attempting to continue anyway...")
    message("If packages are missing, install them manually with:")
    message("  install.packages(PACKAGE_NAME)")
    message("")
  })
}

# Run the main analysis pipeline
message("")
message("=== STARTING PNAS REPLICATION ===")
message("")
source(here::here("analysis", "pnas_script_runner.R"))
message("")
message("=== REPLICATION COMPLETE ===")

